package cn.iune.erp.inventory;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

@Transactional
@Service
public class StorageLedgerServiceImpl implements IStorageLedgerService {
	private final Logger log = LogManager.getLogger(this);

	@Autowired
	private IStorageLedgerDao dao;
	@Autowired
	private IStorageLedgerDetailDao detailDao;
	

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#getAll()
	 */
	@Override
	public List<StorageLedger> getAll(){
		return dao.getAll();
	}
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#getByID(java.lang.String)
	 */
	@Override
	public StorageLedger getByID(String fID) {
		return dao.getByID(fID);
	}
	
	@Transactional
	@Override
	public void insert(StorageLedger obj) {
		dao.insert(obj);
	}

	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#delete(java.lang.String)
	 */
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}

	@Transactional
	@Override
	public void update(StorageLedger obj) {
		dao.update(obj);
	}

	
	@Override
	public StorageLedger getByNo(String recordNo, String enterpriseNo) {
		return dao.getByNo(recordNo, enterpriseNo);
	}

	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException {
		//System.out.println("StorageLedger.save-->"+object.toJSONString());
		/*
		//判断数据（日期型数据是否合格）
		String relationAlias = object.getJSONObject("userdata").getString("relationAlias");
		String relationTypes = object.getJSONObject("userdata").getString("relationTypes");
		System.out.println("StorageLedger.save.relationAlias-->"+relationAlias);
		System.out.println("StorageLedger.save.relationTypes-->"+relationTypes);
		
		String[] cols = relationAlias.split(",");
		String[] types = relationTypes.split(",");
		
		JSONArray data = object.getJSONArray("rows");
		//循环行
		System.out.println("**********行数"+data.size());
		for(int index=0;index<data.size();index++) {
			JSONObject row = data.getJSONObject(index);
			System.out.println("**********"+row.toJSONString());
			//循环列
			for(int i=0;i<cols.length;i++) {
				String type = types[i];
				if("Date".equals(type) || "DateTime".equals(type)) {
					String col = cols[i];
					JSONObject cvalue = row.getJSONObject(col);
					System.out.println("type-->>"+type+"-->>column-->>"+col+"-->>value-->>"+cvalue.get("value"));
					System.out.println("type-->>"+type+"-->>column-->>"+col+"-->>value-->>"+cvalue.get("originalValue"));
				}
			}
		}
		*/
		
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", "StorageLedger");
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			StorageLedger obj = JSON.toJavaObject(javaObject, StorageLedger.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				StorageLedger objNew = dao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}
	
	@Transactional
	@Override
	public JSONObject saveDetail(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", "StorageLedgerDetail");
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			StorageLedgerDetail obj = JSON.toJavaObject(javaObject, StorageLedgerDetail.class);
			if(RowState.NEW.equals(obj.getRowState())){
				detailDao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				detailDao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				StorageLedgerDetail data = detailDao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", data.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}

	
	
	
	///////////////////////业务功能///////////////////////////////////////
	
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#confirm(java.lang.String)
	 */
	@Transactional
	@Override
	public int confirm(String fID) {
		StorageLedger sr = dao.getByID(fID);
		sr.setState("confirm");
		sr.setResultStatus("审核中");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#active(java.lang.String)
	 */
	@Transactional
	@Override
	public int active(String fID) {
		StorageLedger sr = dao.getByID(fID);
		sr.setState("active");
		sr.setResultStatus("待审核");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#close(java.lang.String)
	 */
	@Transactional
	@Override
	public int close(String fID) {
		StorageLedger sr = dao.getByID(fID);
		sr.setStatus("close");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#open(java.lang.String)
	 */
	@Transactional
	@Override
	public int open(String fID) {
		StorageLedger sr = dao.getByID(fID);
		sr.setStatus("open");
		dao.update(sr);
		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#agreeIt(java.lang.String)
	 */
	@Transactional
	@Override
	public int agreeIt(String fID,String usercode,String username, String userId) {
		StorageLedger sr = dao.getByID(fID);
//		System.out.println("fID-->"+fID);
//		System.out.println("sr-->"+sr);

		sr.setAudit("confirm");
		sr.setConfirmDate(Utils.getCurrentDate());
		
		sr.settUsercode(usercode);
		sr.settUsername(username);
		sr.settDatetime(Utils.getCurrentDateTime());
		
		sr.setResultStatus("已审核");

		dao.update(sr);

		return 0;
	}
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#unAgree(java.lang.String)
	 */
	@Transactional
	@Override
	public int unAgree(String fID) {
		StorageLedger sr = dao.getByID(fID);
		//判断是否可以撤销
		
		sr.setAudit("active");
		sr.setConfirmDate(null);
		
		sr.settUsercode(null);
		sr.settUsername(null);
		sr.settDatetime(null);
		
		sr.setResultStatus("审核中");

		dao.update(sr);

		return 0;
	}

	
	@Override
	public JSONObject querySimple(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject data = dao.querySimple(param);
			return data;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", "failure");
			
			return json;
		}
	}
	
	
	//更新明细表最大流水号
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageLedgerService#updateMaxDetailNo(java.lang.String, int)
	 */
	@Transactional
	@Override
	public int updateMaxDetailNo(String fID,int maxDetailNo){
		StorageLedger sr = dao.getByID(fID);
		sr.setMaxDetailNo(maxDetailNo);
		dao.update(sr);
		return 0;
	}
	
	
	@Override
	public StorageLedger packing(
			String billType
			,String billTypeName 
			,String systemCode 
			,int flowType 
			,String revOpay 
			,int direction 
			,String costingCode 
			,String autoCode 
			,String origin 
			,String originName 
			,String billNo 

			,String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		String APPID = null;
//		if(billType.equals("XSCK")){
//			APPID = "8afbf31f51d05a5ca5e5e3e59fd15e99";
//		}
//		if(billType.equals("XSRK")){
//			APPID = "638bbc8d84d6dc6a9ed61d2f9c5ce163";
//		}
//		if(billType.equals("CGRK")){
//			APPID = "154493d129a970fd5aaf035c49040d57";
//		}
//		if(billType.equals("CGCK")){
//			APPID = "e1e167ffecef696b79e6c17fc9b82a9a";
//		}
//		
//		if(billType.equals("SCRK")){
//			APPID = "7b6d529b3e96d122a0e087b63afe3895";
//		}
//		if(billType.equals("SCCK")){
//			APPID = "c3a1021844010d9a7b0d6367e1bdaa1e";
//		}
//		if(billType.equals("WWRK")){
//			APPID = "704ce197f8502b03dc077c5c07aa84d8";
//		}
//		if(billType.equals("WWCK")){
//			APPID = "241f422fd4ebeb2e03c4d3060dddb408";
//		}
//		
//		if(billType.equals("SCFL") || billType.equals("WWFL")){
//			APPID = "fb312876ed0984810120cc26a71fc340";
//		}
//		if(billType.equals("SCTL") || billType.equals("WWTL")){
//			APPID = "50c7aa3657df4a2949a4c51d614d22ad";
//		}

		StorageLedger obj = new StorageLedger();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		//单号
		/*
		Map<String,Object> map = usercenterService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
//		String systemCode = (String) map.get("systemCode");
		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = (String) map.get("origin");
		String originName = (String) map.get("originName");
		if("Y".equals(autoCode)){
			String billNo = (String) map.get("billNo");
			obj.setRecordNo(billNo);
		}
		*/
		if("Y".equals(autoCode)){
			obj.setRecordNo(billNo);
		}
		
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setSystemCode(APPID);
		obj.setFlowType(flowType);
		obj.setRevOpay(revOpay);
//		obj.setDirection(direction);
		obj.setCostingCode(costingCode);
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		obj.setDetailsCount(0);
		obj.setDetailsCountState(0);
		obj.setMaxDetailNo(0);
		
		obj.setVersion(0);
		
		return obj;
	}
	
	
	
	
	@Override
	public JSONObject newData(JSONObject param) {
		return dao.create(param);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
//		String ucode = param.getString("ucode");
//		String uname = param.getString("uname");
//		String uid = param.getString("uid");
		
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			//首先删除子表
			List<StorageLedgerDetail> srds = detailDao.getByMasterID(id);
			for(StorageLedgerDetail srd:srds){
				detailDao.delete(srd.getfID());
			}

			//然后删除主表
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}
	
	@Override
	public JSONObject saveData(JSONObject param) {
		// TODO Auto-generated method stub
		JSONObject data;
		try {
			//保存主表
			data = this.save(param);
			
			//保存从表
			JSONArray slaves = param.getJSONArray("slaves");
			JSONObject slaveParam = slaves.getJSONObject(0);
			
			JSONObject slaveData = this.saveDetail(slaveParam);
			
			JSONArray slaveDatas = new JSONArray();
			slaveDatas.add(slaveData);
			data.put("slaves", slaveDatas);
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.info("ParseException开始打印：");
			e.printStackTrace();
			log.info("e.getMessage()-->>"+e.getMessage());
			log.info("ParseException完成打印。");
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	@Override
	public JSONObject queryData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

	//新增子表
	@Override
	public JSONObject newDataDetail(JSONObject param) {
		return detailDao.create(param);
	}
	
	//查询子表
	@Override
	public JSONObject queryDataDetail(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = detailDao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	
	
}
